﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_PERMISSION.Base;

namespace ERP_RORZE_PERMISSION.Forms
{
    public partial class frm_PermissionConfig : DevExpress.XtraEditors.XtraForm
    {
        private DataTable dtPermissionGroup;
        private int userGroup;
        private LogUtils log;
        private bool loaded;
        public frm_PermissionConfig()
        {
            InitializeComponent();
        }

        private void frm_PermissionConfig_Load(object sender, EventArgs e)
        {
            BindDataUserGroup();
            log = new LogUtils();
            loaded = true;
        }

        private void BindDataUserGroup()
        {
            DataTable dt = BaseDAO.ExecuteQuery("Select [GroupID], [GroupName] from [222_UserGroup] order by [GroupName]");
            DataRow row = dt.NewRow();

            row["GroupName"] = "<Select...>";
            row["GroupID"] = DBNull.Value;
            dt.Rows.InsertAt(row, 0);

            cmbUserGroup.DataSource = dt;
            cmbUserGroup.DisplayMember = "GroupName";
            cmbUserGroup.ValueMember = "GroupID";
            cmbUserGroup.SelectedItem = cmbUserGroup.Items[0];

        }

        private void cmbUserGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!loaded) return;


            if (!Utilities.IsNullOrEmpty(cmbUserGroup.SelectedValue) || cmbUserGroup.SelectedItem != cmbUserGroup.Items[0])
            {
                userGroup = int.Parse(cmbUserGroup.SelectedValue.ToString());
                this.dtPermissionGroup = BaseDAO.ExecuteQuery("SELECT distinct " +
                                                              "case when CHARINDEX('.', [FunctionName])>0 " +
                                                              "     then LEFT([FunctionName], CHARINDEX('.', [FunctionName])-1) " +
                                                              "     else '<Error>' end  as [RoleGroup] " +
                                                              "FROM [222_Functions]");
                listPermissionGroup.DataSource = dtPermissionGroup;
                listPermissionGroup.DisplayMember = "RoleGroup";
                listPermissionGroup.ValueMember = "RoleGroup";

                listPermissionGroup.SelectedItem = listPermissionGroup.Items[0];
            }
            else
            {
                listPermissionGroup.DataSource = null;
                gridControl1.DataSource = null;
            }
        }

        private void listPermissionGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = BaseDAO.ExecuteQuery("   Select " +
                                                 "   case when   [Permission].UserGroupID = '" + userGroup + "'" +
                                                 "       then cast(1 as bit) " +
                                                 "       else cast(0 as bit) " +
                                                 "   end as [Role] " +
                                                 "   ,[222_Functions].FunctionID, [222_Functions].FunctionName " +
                                                 " from [222_Functions] " +
                                                 "   left join  " +
                                                 "   ( " +
                                                 "       select [222_Permission].FunctionID, [222_Permission].UserGroupID, [222_UserGroup].GroupName " +
                                                 "       from [222_Permission]  " +
                                                 "           left join [222_UserGroup] on [222_UserGroup].GroupID = [222_Permission].UserGroupID " +
                                                 "           where [222_Permission].UserGroupID = '" + userGroup + "'" +
                                                 "   ) [Permission] " +
                                                 "   on [Permission].FunctionID = [222_Functions].FunctionID " +
                                                 " where [222_Functions].FunctionName like N'" + listPermissionGroup.SelectedValue + ".%'");
            gridControl1.DataSource = dt;
            gridView1.OptionsBehavior.Editable = true;
            gridView1.Columns["Role"].OptionsColumn.AllowEdit = true;
            gridView1.Columns["FunctionID"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["FunctionName"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["UserGroupID"].OptionsColumn.AllowEdit = false;
            gridView1.BestFitColumns();
        }

        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value != null && gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["FunctionID"]) != null)
            {
                bool role = (bool)e.Value;

                string functionID = gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["FunctionID"]).ToString();
                if (role)
                {
                    DataTable dtCheck =
                        BaseDAO.ExecuteQuery("Select * from [222_Permission] where [222_Permission].FunctionID = '" +
                                             functionID + "' and [222_Permission].UserGroupID ='" + this.userGroup + "'");
                    if (dtCheck.Rows.Count == 0)
                    {
                        string insert = "INSERT INTO [222_Permission] " +
                                        "           ([FunctionID] " +
                                        "           ,[UserGroupID] " +
                                        "           ,[Status]) " +
                                        "     VALUES " +
                                        "           ('" + functionID + "'" +
                                        "           ,'" + this.userGroup + "'" +
                                        "           ,'1' )";
                        if (BaseDAO.ExecuteNonQuery(insert) < 1)
                            MessageBox.Show("Gặp lỗi khi cập nhật quyền.");
                        else
                        {

                            //write Log
                            log.Table = LogConstant.Table.SystemAdmin.Permission;
                            log.Task = LogConstant.Task.Insert;
                            log.Description = "FunctionID: " + functionID + "; UserGroupID: " + this.userGroup;
                            log.WriteLog();

                        }
                    }
                }
                else
                {
                    string delete = "Delete from [222_Permission] where [222_Permission].FunctionID = '" +
                                             functionID + "' and [222_Permission].UserGroupID ='" + this.userGroup + "'";
                    if (BaseDAO.ExecuteNonQuery(delete) < 1)
                        MessageBox.Show("Gặp lỗi khi cập nhật quyền.");
                    else
                    {

                        //write Log
                        log.Table = LogConstant.Table.SystemAdmin.Permission;
                        log.Task = LogConstant.Task.Delete;
                        log.Description = "FunctionID: " + functionID + "; UserGroupID: " + this.userGroup;
                        log.WriteLog();

                    }
                }
            }


        }
    }
}